package ServletDemo2;


import entity.Administrators;
import util.GokJDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginAdminServlet")
public class LoginAdminServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        String name = request.getParameter("name");
        String pd = request.getParameter("pd");

        // 查询管理员数据库
        Administrators administrators = GokJDBCUtil.queryForObject(
                "SELECT * FROM administrators WHERE name = ? AND pd = ?",
                Administrators.class, name, pd);
        System.out.println("111");
        if (administrators != null) {
            // 登录成功，设置会话
            HttpSession session = request.getSession();
            session.setAttribute("name", name);
            System.out.println("221");
            // 转发到欢迎页面
            request.getRequestDispatcher("home.jsp").forward(request, response);
        } else {
            // 登录失败，设置错误消息
            request.setAttribute("msg", "用户名或密码错误!");
            // 返回登录页面
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }



    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}